import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

part_inv_router = APIRouter(prefix="/part/partInv", tags=["备件库存管理"], dependencies=[Depends(oauth2_scheme)])


class SparePartInventoryQueryRequest(PaginationBase):
    fmovdate: Optional[str] = Field("", description="库存月份(格式如'2025-06')")
    fpartname: Optional[str] = Field("", description="备件ID")


@part_inv_router.get("/list", summary="")
def list_part_inv(search, db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from tc_part_inv where 1=1"
    if search.fpartname != "":
        sql = sql + " and fpartid = :fpartname "
        param["fpartname"] = search.fpartname
    if search.fmovdate != "":
        sql = sql + " and fmonth = :fmovdate "
        param["fmovdate"] = search.fmovdate
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fmonth,fpartid,fbegqty,frecqty,foutqty,finqty,fmrkqty,fbalqty"
    sql = sql + " from tc_part_inv where 1=1"
    if search.fpartname != "":
        sql = sql + " and fpartid = :fpartname "
        param["fpartname"] = search.fpartname
    if search.fmovdate != "":
        sql = sql + " and fmonth = :fmovdate "
        param["fmovdate"] = search.fmovdate
    if search.order == "desc":
        sql = sql + " order by  fmonth,fpartid desc "
    else:
        sql = sql + " order by  fmonth,fpartid "
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fmonth'] = data[key][0]
        d1['fpartid'] = data[key][1]
        d1['fbegqty'] = data[key][2]
        d1['frecqty'] = data[key][3]
        d1['foutqty'] = data[key][4]
        d1['finqty'] = data[key][5]
        d1['fmrkqty'] = data[key][6]
        d1['fbalqty'] = data[key][7]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)
